package com.tsingteng.cosfun.ui.cosfun;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseActivity;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.ImgBean;
import com.tsingteng.cosfun.bean.PersonBean;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.ui.cosfun.adapter.TipOffsImgAdapter;
import com.tsingteng.cosfun.ui.cosfun.contract.FeedBackContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.FeedbackPresenter;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.PhotoUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UploadBitmapUtil;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.TagsGridView;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TipOffsActivity extends BaseActivity implements View.OnClickListener, TipOffsImgAdapter.ImgOnClickListener, FeedBackContract.IfeedBackView {
    TipOffsImgAdapter tipOffsImgAdapter = null;
    TagsGridView tagsGridView = null;
    TextView reason_tv = null;
    TextView enter_tv = null;
    ImageView back_img = null;
    EditText opus_link_et;
    EditText des_et;
    List<ImgBean> list = null;
    private FeedbackPresenter feedbackPresenter;

    @Override
    protected void initView() {
        feedbackPresenter = new FeedbackPresenter(this);
        back_img = findViewById(R.id.activity_tip_offs_title_back);
        back_img.setOnClickListener(this);
        reason_tv = findViewById(R.id.activity_tip_offs_reason_tv);
        opus_link_et = findViewById(R.id.activity_tip_offs_opus_et);
        des_et = findViewById(R.id.activity_tip_offs_des_et);
        tagsGridView = findViewById(R.id.activity_tip_offs_img_grid);
        enter_tv = findViewById(R.id.activity_tip_offs_enter);
        enter_tv.setOnClickListener(this);

        list = new ArrayList<>();
        handleImg("");
        tipOffsImgAdapter = new TipOffsImgAdapter(this, this, list, this);
        tagsGridView.setAdapter(tipOffsImgAdapter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tip_offs_main;
    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_tip_offs_title_back:
                this.finish();
                break;
            case R.id.activity_tip_offs_enter:
                this.finish();
                break;
        }
    }

    public void handleImg(String url) {
        if (list == null) {
            return;
        }
        for (ImgBean imgBean : list) {
            if (imgBean.getType() == 0) {
                list.remove(imgBean);
                break;
            }
        }
        if (list.size() == 4) {
            return;
        }
        if (!TextUtils.isEmpty(url)) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(1);
            imgBean.setPath(url);
            list.add(imgBean);
        }
        if (list.size() < 4) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(0);
            list.add(imgBean);
        }
        if (tipOffsImgAdapter != null)
            tipOffsImgAdapter.notifyDataSetChanged();
    }

    public void delImg(int index) {
        if (list == null) {
            return;
        }
        for (ImgBean imgBean : list) {
            if (imgBean.getType() == 0) {
                list.remove(imgBean);
                break;
            }
        }
        list.remove(index);

        if (list.size() < 4) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(0);
            list.add(imgBean);
        }

        if (tipOffsImgAdapter != null)
            tipOffsImgAdapter.notifyDataSetChanged();
    }

    String[] url = {"http://t2.hddhhn.com/uploads/tu/201804/9999/336265b400.jpg", "http://t2.hddhhn.com/uploads/tu/201804/9999/9b92c5e841.jpg", "http://t2.hddhhn.com/uploads/tu/201804/9999/d4b95871f8.jpg", "http://t2.hddhhn.com/uploads/tu/201804/9999/487bcece29.jpg", "http://t2.hddhhn.com/uploads/tu/201804/9999/fedf734cba.jpg"};
    private Uri imageUri;

    @Override
    public void add() {
        File file = new File(VideoUtils.photoSavePathCache, System.currentTimeMillis() + ".png");
        if (PhotoUtils.hasSdcard()) {
            imageUri = Uri.fromFile(file);
            //通过FileProvider创建一个content类型的Uri
         /*   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, file);
            }*/
            PhotoUtils.getInstance().showPopupWindow(this, tagsGridView, imageUri);
        } else {
            ToastUtils.showToast("设备没有SD卡！");
        }
    }

    /**
     * 图片选择及拍照结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PhotoUtils.CODE_GALLERY_REQUEST:// 相册
                if (data == null) {
                    return;
                }
                imageUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    imageUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, new File(imageUri.getPath()));
//                }
                feedbackPresenter.getSignTureData("1");
                break;
            case PhotoUtils.CODE_CAMERA_REQUEST:// 拍照
                feedbackPresenter.getSignTureData("1");
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case PhotoUtils.CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.takePicture(this, imageUri, PhotoUtils.CODE_CAMERA_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打开相机！！");
                }
                break;

            }
            case PhotoUtils.STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, PhotoUtils.CODE_GALLERY_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打操作SDCard！！");
                }
                break;
        }
    }

    @Override
    public void del(int index) {
        delImg(index);
    }

    @Override
    public void onSuccess(BaseDataBean<PersonBean> personBeanBaseDataBean) {

    }

    @Override
    public void UploadVideo(VideoSignBean data) {
        String pathCompress = VideoUtils.photoSavePathCache + System.currentTimeMillis() + ".png";
        int state = UploadBitmapUtil.compress(PhotoUtils.getRealPathFromURI(this, imageUri), pathCompress, UploadBitmapUtil.SMALL_IMAGE_COMPRESS);
        if (state == UploadBitmapUtil.SUCCESS) {
            // 显示进度条
            UploadManager uploadManager = new UploadManager();
            uploadManager.put(pathCompress,
                    String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).

                            hashCode() + data.getPath(),
                    data.getSign(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (info.isOK()) {
                                        ToastUtils.showToast("上传成功");
                                        String path = data.getDomain() +  "/" +key;
                                        handleImg(path);
                                    } else {
                                        ToastUtils.showToast(info.error);
                                    }
                                }
                            });

                        }
                    }, null);

        } else if (state == UploadBitmapUtil.FILE_NOT_FOUND) {
            ToastUtils.showToast("文件夹找不到");
        } else if (state == UploadBitmapUtil.GEN_BITMAP_FAILURE) {
            ToastUtils.showToast("生成图像失败");
        } else if (state == UploadBitmapUtil.IO_EXCEPTION) {
            ToastUtils.showToast("存储文件失败");
        }
    }

    @Override
    public void showLoading(String msg) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }
}
